package org.playground.booking.controller;

import io.swagger.annotations.Api;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.playground.booking.dto.EmailSendingRequestDto;
import org.playground.booking.utils.PlaygroundBookingException;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * Created by root on 18-4-8.
 */
@Api
@RestController
@RequestMapping(path = "/api/mail/*")
public class EmailController {

    private static Logger LOGGER = Logger.getLogger(BookingController.class);

    @CrossOrigin(origins = {"http://localhost:63342","https://www.fanruohong.cn","null"})
    @RequestMapping(path = "send",produces = "application/json",method = RequestMethod.POST)
    public String sendEmail(
            @RequestBody EmailSendingRequestDto request) throws IOException, PlaygroundBookingException {
        String url = "https://api.sendgrid.com/v3/mail/send";
        String apiKey="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";
        String entityString = "{\"personalizations\": [{\"to\": [{\"email\": \""+request.getTo()+"\"}]}]," +
                "\"from\": {\"email\": \""+request.getFrom()+"\"}," +
                "\"subject\": \""+request.getName()+"\"," +
                "\"content\": [{\"type\": \"text/plain\", " +
                "\"value\": \""+request.getMessage()+"\"}]}";




        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost post = new HttpPost(url);
        post.setHeader("Authorization","Bearer "+apiKey);
        post.setHeader("Content-Type","application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(entityString,charSet);

        post.setEntity(entity);

        CloseableHttpResponse response=null;

        String responseString="";

        try{
            response = httpClient.execute(post);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK||state==HttpStatus.SC_ACCEPTED) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                responseString = "{\"response\":"+jsonString+"}";
                LOGGER.info(responseString);
            }
            else{
                LOGGER.error("Return status :"+state+"("+url+")");
                throw new PlaygroundBookingException("Return status :"+state+"("+url+")");
            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    throw new PlaygroundBookingException(e.getMessage());
                }
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
                throw new PlaygroundBookingException(e.getMessage());
            }
            return responseString;
        }
    }
}
